<template>
  <div>
    <el-card class="margin_30" shadow="always" :body-style="{ padding: '20px' }">
      <div slot="header">
        <span>{{ $route.params.id ? "编辑" :'新增' }}文章</span>
      </div>
      <!-- card body -->
      <el-form ref="form" :rules="rules" :model="form" label-width="120px" size="mini">
        <el-row>
          <el-col :span="8">
            <el-form-item label="作者" prop="author">
              <el-input v-model="form.author" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否显示">
              <el-switch v-model="form.isShow" />

            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="17" :offset="0">
            <el-form-item label="摘要">
              <el-input
                v-model="form.summary"
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
              />

            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="17" :offset="0">
            <el-form-item label="封面图片上传">
              <el-upload
                action="/lejuAdmin/material/uploadFileOss"
                :headers="headers"
                :on-success="getImg"
                :show-file-list="false"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                <div>
                  <img :src="form.coverImg" alt="">
                </div>

              </el-upload>

            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="切换富文本类型">
          <Tinymce v-model="form.content1" />
          <!-- <mavon-editor ref="md" v-model="form.content1" @change="getResult" @imgAdd="$imgAdd" /> -->
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">立即创建</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>

    </el-card>

  </div>
</template>

<script>
import {
  getToken
} from '@/utils/myAuth.js'
import tinymce from '@/components/Tinymce/index'
import {
  uploadFileOss,
  addArticle,
  productArticle,
  updateArticle
} from '@/api/contentManage/addArticle/index'
export default {
  components: {
    Tinymce: tinymce
  },
  data() {
    var checkTitle = (rule, value, callback) => {
      console.log(value)
      if (value.length < 5) {
        callback()
      } else {
        callback(new Error('标题长度不能大于5'))
      }
      // if (value === '') {
      //   callback(new Error('请再次输入密码'));
      // } else if (value !== this.ruleForm.pass) {
      //   callback(new Error('两次输入密码不一致!'));
      // } else {
      //   callback();
      // }
    }
    return {
      headers: {
        token: getToken()
      },
      content: '',
      form: {
        'author': '',
        'collectCount': '',
        'content1': '',
        'content2': '',
        'coverImg': '',
        'createTime': '',
        'editorType': 1,
        'id': '',
        'isShow': '',
        'modifyTime': '',
        'summary': '',
        'title': '',
        'viewCount': '',
        'zanCount': ''
      },
      rules: {
        // required 必填
        // message 校验失败提示的文字内容
        // trigger 触发方式  失焦触发
        author: [
          { required: true, message: '请输入作者姓名', trigger: 'blur' },
          { min: 3, max: 5, message: '作者姓名长度在3-5之间', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          // { validator: this.checkTitle, trigger: 'blur' }
          { validator: checkTitle, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    if (this.$route.params.id) {
      productArticle(this.$route.params.id)
        .then(res => {
          console.log(res)
          res.data.productArticle.isShow = !!res.data.productArticle.isShow
          this.form = res.data.productArticle
        })
    }
  },
  methods: {
    getResult(value, render) {
      console.log(value, render)
      this.form.content2 = render
    },
    $imgAdd(pos, $file) {
      // 第一步.将图片上传到服务器.
      var formdata = new FormData()
      formdata.append('file', $file)
      uploadFileOss(formdata)
        .then(res => {
          this.$refs.md.$img2Url(pos, res.data.fileUrl)
        })
      // axios({
      //   url: 'server url',
      //   method: 'post',
      //   data: formdata,
      //   headers: { 'Content-Type': 'multipart/form-data' }
      // }).then((url) => {
      //   // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
      //   /**
      //          * $vm 指为mavonEditor实例，可以通过如下两种方式获取
      //          * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
      //          * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
      //          */
      //   $vm.$img2Url(pos, url)
      // })
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        console.log(valid)
        if (valid) {
          var formData = JSON.parse(JSON.stringify(this.form))
          formData.isShow = formData.isShow ? 1 : 0
          if (this.$route.params.id) {
            updateArticle(formData)
              .then(res => {
                console.log(res)
                this.$router.push({ name: 'contentManageArticleList' })
              })
          } else {
            addArticle(formData)
              .then(res => {
                console.log(res)
                this.$router.push({ name: 'contentManageArticleList' })
              })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
      // addArticle(this.form)
    },
    getImg(val) {
      console.log(val)
      this.form.coverImg = val.data.fileUrl
    }
    // checkTitle(rule, value, callback) {
    //   console.log(value)
    // }
  }
}
</script>

<style scoped lang="scss">

</style>
